package com.zxy.supplier_system.server.entity

import jakarta.persistence.*
import org.hibernate.annotations.DynamicInsert
import org.hibernate.annotations.DynamicUpdate
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
import java.time.OffsetDateTime

/**
 * 卖场订单
 */
@Entity
@EntityListeners(AuditingEntityListener::class)
@DynamicUpdate
@DynamicInsert
class MarketOrder : Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int = 0

    @Column(nullable = false)
    lateinit var number: String

    @CreatedDate
    lateinit var createdDateTime: OffsetDateTime

    @CreatedBy
    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    lateinit var employee: Employee

    @LastModifiedDate
    var lastModifiedDateTime: OffsetDateTime? = null

    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    lateinit var market: Market

    @OneToMany(orphanRemoval = true, mappedBy = "marketOrder", cascade = [CascadeType.ALL])
    @OrderBy(value = "sequence asc")
    var goodsList: MutableList<MarketOrderItem> = mutableListOf()

    var submitDateTime: OffsetDateTime? = null

    @OneToOne
    @PrimaryKeyJoinColumn
    var deliveryOrder: MarketDeliveryOrder? = null

    enum class Status {
        WAIT_SUBMIT,
        SUBMITTED,
        DELIVERY,
    }

    @get:Transient
    val status: Status
        get() {
            return if (submitDateTime == null) {
                Status.WAIT_SUBMIT
            } else if (deliveryOrder == null) {
                Status.SUBMITTED
            } else {
                Status.DELIVERY
            }
        }


}